//
//  HomePage2ViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-6-16.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "HomePage2ViewController.h"

#import "LoginPageViewController.h"
#import "NewsViewController.h"
#import "AppDelegate.h"

#import "UserSession.h"
#import "UserPrivateInfoVO.h"
#import "WetherInfoVO.h"
#import "ChatListViewController.h"
#import "PublishAirticleViewController.h"
#import "NearbyFriendsViewController.h"
#import "CircleDetailViewController.h"
#import "PersonalInfoViewController.h"
#import "MoreViewController.h"
#import "MyCommentsViewController.h"
#import "GolfFriendCircleCell.h"

#import "CommonUtility.h"
#import "DateUtility.h"
#import "AppsEngine.h"
#import <CoreLocation/CoreLocation.h>
#import "AppsLocationManager.h"
#import "SVProgressHUD.h"
#import "UIImageView+MJWebCache.h"
#import "CacheDaoForCircleContent.h"
#import "GFVOParser.h"

@interface HomePage2ViewController ()<ToolbarViewControllerDelegate,UITableViewDataSource,UITableViewDelegate> {
    NewsViewController *newsView;
    NSMutableArray *articlesArray;
    CacheDaoForCircleContent *contentCacheManager;
    NSString *currentIndex;
    GolfFriendCircleCell *sampleCell;
    bool needSvp;
    
    //隐藏tabbar的位置标记
    float hpScrollViewLastOffset;
}

@end

@implementation HomePage2ViewController

#pragma mark - life-cycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    currentIndex = Initial_index;
    
    [self initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
    if (ShowToolbarInWindow) {
        [toolBarView.view removeFromSuperview];
    }
    else {
        if (!toolBarView) {
            toolBarView = [[ToolbarViewController alloc] init];
            CGRect gfToolbarFrame = toolBarView.view.frame;
            gfToolbarFrame.origin.y = self.view.frame.size.height - gfToolbarFrame.size.height;
            toolBarView.view.frame = gfToolbarFrame;
            toolBarView.delegate = self;
            [self.view addSubview:toolBarView.view];
        }
    }
    
    [self initData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

#pragma mark - Private
- (void)initData {
    labelUserName.text = [[UserSession shareUserSession] getUserName];
    labelMotto.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"motto"];
    
    imgAvatar.layer.cornerRadius = imgAvatar.frame.size.width / 2.0;
    NSString *avatarLink = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"avatar"];
    if ([avatarLink stringByMatching:Qiniu_Domain]) {
        avatarLink = GetQiniuResizeImageLink(avatarLink, 160);
    }
    [imgAvatar setImageURLStr:avatarLink placeholder:Default_Avatar];
    
    
    labelDate.text = getStringFromDate(@"yyyy-MM-dd", [NSDate date]);
    labelWeek.text = getEnglishWeekdayFromDate([NSDate date]);
    
    //读取缓存数据，再请求网上数据
    if (!contentCacheManager) {
        contentCacheManager = [CacheDaoForCircleContent shareCacheDaoForCircleContent];
    }
    NSMutableArray *cDataArray = [contentCacheManager getCacheDataLimitRow:NSMakeRange(0, 20)];
    
    if (cDataArray && [cDataArray count] > 0) {
        [articlesArray removeAllObjects];
        articlesArray = [self sortArrayByRecordIdDesc:cDataArray];
    }
    else {
        //显示没有数据的页面
        [self.view addSubview:noDataView];
    }
    
    needSvp = NO;
    [self refreshData];
}

- (void)initView {
    
    if (!newsView) {
        newsView = [[NewsViewController alloc] init];
    }
    [newsView.view setClipsToBounds:YES];
    
    [self weatherDidRefreshed];
    
    CGRect tbRect = tbView.frame;
    if (iPhone5) {
        tbRect.size.height = 548.f;
    }
    else {
        tbRect.size.height = 460.f;
    }
    if (ios7OrLater) {
        tbRect.origin.y = 20;
    }
    
    [tbView setFrame:tbRect];
    tbView.separatorColor = [UIColor clearColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weatherDidRefreshed) name: @"WeatherForcast" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollToTop) name:Notification_homepage_clicked object:nil];
    
    //For circle
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articlePublishedNotificationDidRecieve:) name:Notification_Article_Published object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articleCommentedNotificationDidRecieve:) name:Notification_Article_Comment_Published object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articleDeletedNotificationDidRecieve:) name:Notification_Article_Deleted object:nil];
}

- (void)scrollToTop {
    //滑动到顶部
    [tbView setContentOffset:CGPointZero animated:YES];
}

- (void)weatherDidRefreshed {
    //refresh labels
    NSUserDefaults *usd = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [usd objectForKey:@"weatherInfo"];
    WetherInfoVO *wInfo = [[WetherInfoVO alloc] init];
    [wInfo dictionaryToWeatherInfoVO:dict];
    
    if (wInfo.cityName && wInfo.cityName.length > 0 ) {
        [labelCityName setText:wInfo.cityName];
    }
    
    if (wInfo.currentTemp && wInfo.currentTemp.length > 0) {
        [labelTemp setText:[NSString stringWithFormat:@"%@℃",wInfo.currentTemp]];//℃
    }
    
    if (wInfo.currentWeather && wInfo.currentWeather.length > 0) {
        [labelWeather setText:simplifyWeather(wInfo.currentWeather)];
    }
    
    if (wInfo.currentWeatherIcon && wInfo.currentWeatherIcon.length > 0) {
        [imgWeather0 setImage:[UIImage imageNamed:wInfo.currentWeatherIcon]];
    }
    
    if ([wInfo.sixDaysWeather count] > 1) {
        NSString *day1Weather = [wInfo.sixDaysWeather objectAtIndex:1];
        [imgWeather1 setImage:[UIImage imageNamed:getWeatherIcon(day1Weather,NO)]];
    }
    
    if ([wInfo.sixDaysWeather count] > 2) {
        NSString *day2Weather = [wInfo.sixDaysWeather objectAtIndex:2];
        [imgWeather2 setImage:[UIImage imageNamed:getWeatherIcon(day2Weather,NO)]];
    }
    
    if ([wInfo.sixDaysWeather count] > 3) {
        NSString *day3Weather = [wInfo.sixDaysWeather objectAtIndex:3];
        [imgWeather3 setImage:[UIImage imageNamed:getWeatherIcon(day3Weather,NO)]];
    }
    
    NSDate *date = [NSDate date];
    NSDate *date1 = [date dateByAddingTimeInterval:DAY_OF_SECONDS];
    NSDate *date2 = [date1 dateByAddingTimeInterval:DAY_OF_SECONDS];
    NSDate *date3 = [date2 dateByAddingTimeInterval:DAY_OF_SECONDS];
    [labelDate1 setText:getStringFromDate(@"MM月dd", date1)];
    [labelDate2 setText:getStringFromDate(@"MM月dd", date2)];
    [labelDate3 setText:getStringFromDate(@"MM月dd", date3)];
}


- (void)refreshTableView {
    [noDataView removeFromSuperview];
    [tbView reloadData];
}

- (NSMutableArray*)sortArrayByRecordIdDesc:(NSMutableArray*)_arr {
    NSArray *sortedArr = [_arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CircleContentVO *cVo1 = (CircleContentVO*)obj1;
        CircleContentVO *cVo2 = (CircleContentVO*)obj2;
        
        if ([cVo1.articleId integerValue] < [cVo2.articleId integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        else if ([cVo1.articleId integerValue] > [cVo2.articleId integerValue]){
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

- (NSMutableArray*)removeSameItemInArray:(NSMutableArray*)_arr {
    NSMutableDictionary *rDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [_arr count]; i++) {
        CircleContentVO *cVo = [_arr objectAtIndex:i];
        [rDict setObject:cVo forKey:cVo.articleId];
    }
    
    NSMutableArray *rArr = [[NSMutableArray alloc] init];
    NSEnumerator *_enum = [rDict keyEnumerator];
    for (NSString *key in _enum) {
        [rArr addObject:[rDict objectForKey:key]];
    }
    return rArr;
}

//获取Cell的高度
- (float)getCellHeightWithContent:(CircleContentVO*)cVo {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"GolfFriendCircleCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getContentHeight:cVo];
}


#pragma mark - Button Action
- (IBAction)goToPersonalView:(id)sender {
    PersonalInfoViewController *pVc = [[PersonalInfoViewController alloc] init];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[[UserSession shareUserSession] getUserPublicInfo]];
    if ([dict objectForKey:@"uId"]) {
        [dict setObject:[dict objectForKey:@"uId"] forKey:@"userId"];
    }
    pVc.userInfo = dict;
    [self.navigationController pushViewController:pVc animated:YES];
}

#pragma mark - Over write parant's Methors
- (void)refreshData {
    NSLog(@">>>>>>>>>>>  Refresh begin <<<<<<<<<<<<<<");
    currentIndex = @"-1";
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys://[[UserSession shareUserSession] getUserId],@"userId",
                                 currentIndex,@"articleId", nil];
    
    if ([[UserSession shareUserSession] getUserId]) {
        [dict setObject:[[UserSession shareUserSession] getUserId] forKey:@"userId"];
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetCircleContent" param:dict onCompletion:^(id jsonResponse) {
        [self endRefreshing];
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            if (needSvp) {
                [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
            }
            needSvp = YES;
            
            NSMutableArray *arr1 = [[GFVOParser shareParser] paseDataForCircleContentArray:jsonResponse];
            if (!arr1 || [arr1 count] <= 0) {
                NSLog(@"没有数据了...");
            }
            else {
                [articlesArray removeAllObjects];
                [articlesArray addObjectsFromArray:arr1];
                articlesArray = [self removeSameItemInArray:articlesArray];
                articlesArray = [self sortArrayByRecordIdDesc:articlesArray];
                [contentCacheManager updateCacheDataWithCircleContentArray:articlesArray];
                [self refreshTableView];
                CircleContentVO *cVo = [articlesArray lastObject];
                currentIndex = cVo.articleId;
            }
        }
        else {
            NSLog(@"刷新失败");
            if (needSvp) {
                [SVProgressHUD showErrorWithStatus:@"刷新失败"];
            }
            needSvp = YES;
        }
        
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        if (needSvp) {
            [SVProgressHUD showErrorWithStatus:@"加载更多失败!"];
        }
        needSvp = YES;
        [self endRefreshing];
    } method:@"GET"];
}

- (void)loadMoreData {
    NSLog(@">>>>>>>>>>>  Load More begin <<<<<<<<<<<<<<");
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys://[[UserSession shareUserSession] getUserId],@"userId",
                                 currentIndex,@"articleId", nil];
    if ([[UserSession shareUserSession] getUserId]) {
        [dict setObject:[[UserSession shareUserSession] getUserId] forKey:@"userId"];
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetCircleContent" param:dict onCompletion:^(id jsonResponse) {
        [self endRefreshing];
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"加载成功");
            NSMutableArray *arr1 = [[GFVOParser shareParser] paseDataForCircleContentArray:jsonResponse];
            if (!arr1 || [arr1 count] <= 0) {
                NSLog(@"已加载到最后一页");
                [SVProgressHUD showSuccessWithStatus:@"已加载到最后一页"];
            }
            else {
                int oldIndex = [articlesArray count] + 2;
                [articlesArray addObjectsFromArray:arr1];//加入原数组中
                articlesArray = [self removeSameItemInArray:articlesArray];
                articlesArray = [self sortArrayByRecordIdDesc:articlesArray];
                [contentCacheManager updateCacheDataWithCircleContentArray:articlesArray];
                [self refreshTableView];
                CircleContentVO *cVo = [articlesArray lastObject];
                currentIndex = cVo.articleId;
                if (oldIndex < [articlesArray count]) {
                    [tbView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:oldIndex inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                }
                
            }
        }
        else {
            NSLog(@"加载更多失败");
            [SVProgressHUD showErrorWithStatus:@"加载更多失败!"];
        }
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        [SVProgressHUD showErrorWithStatus:@"加载更多失败!"];
        [self endRefreshing];
    } method:@"GET"];
}

#pragma mark - ToolbarViewControllerDelegate
- (void)btnClicked:(id)sender {
    UIButton *btn = (UIButton*)sender;
    
    if (btn.tag == 101) {
        [self scrollToTop];
    }
    else if (btn.tag == 102) {
        ChatListViewController *cVc = [[ChatListViewController alloc] init];
        [self.navigationController pushViewController:cVc animated:YES];
    }
    else if (btn.tag == 103) {
        PublishAirticleViewController *wVc = [[PublishAirticleViewController alloc] init];
        [self.navigationController pushViewController:wVc animated:YES];
    }
    else if (btn.tag == 104) {
        MyCommentsViewController *mVc = [[MyCommentsViewController alloc] init];
        [self.navigationController pushViewController:mVc animated:YES];
    }
    else if (btn.tag == 105) {
        [[APP_DELEGATE sidePannelController] showLeftPanelAnimated:YES];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [articlesArray count] + 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 2) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            [cell addSubview:personalView];
            return cell;
        }
        else if (indexPath.row == 1) {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            [cell addSubview:newsView.view];
            return cell;
        }
    }
    
    static NSString *CellIdentifier = @"GolfFriendCircleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GolfFriendCircleCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        if (indexPath.row - 2 < [articlesArray count]) {
            [cell performSelector:@selector(setDataInfo:) withObject:[articlesArray objectAtIndex:indexPath.row - 2]];
        }
    }
    if([cell respondsToSelector:@selector(setDelegate:)]){
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row <= 1) {
        return 180.f;
    }
    if (indexPath.row - 2 < [articlesArray count]) {
        return [self getCellHeightWithContent:[articlesArray objectAtIndex:indexPath.row - 2]];
    }
    else {
        return 0;
    }
    
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//}
//
//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"MyCommentCell selected:%d",indexPath.row);
//}


- (void)articlePublishedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        [articlesArray insertObject:[notification object] atIndex:0];
        [self refreshTableView];
    }
    else {
        [self performSelector:@selector(refreshData) withObject:nil afterDelay:2.0];
    }
    
}

- (void)articleCommentedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        CircleContentVO *cVo = [notification object];
        for (int i = 0; i < [articlesArray count]; i++) {
            CircleContentVO *c1 = [articlesArray objectAtIndex:i];
            if ([c1.articleId isEqualToString:cVo.articleId]) {
                [articlesArray replaceObjectAtIndex:i withObject:c1];
            }
        }
        [self refreshTableView];
    }
    else {
        [self performSelector:@selector(refreshData) withObject:nil afterDelay:2.0];
    }
    
}

- (void)articleDeletedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        CircleContentVO *cVo = [notification object];
        for (int i = 0; i < [articlesArray count]; i++) {
            CircleContentVO *c1 = [articlesArray objectAtIndex:i];
            if ([c1.articleId isEqualToString:cVo.articleId]) {
                [articlesArray removeObject:cVo];
                [[CacheDaoForCircleContent shareCacheDaoForCircleContent] deleteArticleContent:cVo];
                [SVProgressHUD showSuccessWithStatus:@"删除成功!"];
                break;
            }
        }
    }
    [self performSelector:@selector(refreshTableView) withObject:nil afterDelay:1.0];
}

#pragma mark - 隐藏tabbar
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    hpScrollViewLastOffset = scrollView.contentOffset.y;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < hpScrollViewLastOffset) {
        //向上,底部栏出现
        [toolBarView.view setHidden:NO];
    }
    else if (scrollView.contentOffset.y > hpScrollViewLastOffset){
        //向下,底部栏消失
        [toolBarView.view setHidden:YES];
    }
}


@end
